//
//  AppDelegate.swift
//  Hyphenate-Demo-Swift
//
//  Created by dujiepeng on 2017/6/12.
//  Copyright © 2017 dujiepeng. All rights reserved.
//

import UIKit
import Hyphenate
import UserNotifications
import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, EMClientDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        //notifcatios
        UMessage.start(withAppkey: "5ae629b1b27b0a6de9000834", launchOptions: launchOptions)
        
        ///加入友盟统计
        
        UMConfigure.setEncryptEnabled(true)
        UMConfigure.setLogEnabled(true)
        UMConfigure.initWithAppkey("5c2c487cf1f55661e4000118", channel: "App Store")
        UIApplication.shared.registerForRemoteNotifications()
        
        registerRemoteNotification()
        
        UMessage.setLogEnabled(true)
        //notifcations end
        
        IQKeyboardManager.shared.enable = true
        UITabBar.appearance().tintColor = KermitGreenTwoColor
        UINavigationBar.appearance().tintColor = AlmostBlackColor
        
        let options = EMOptions.init(appkey: "1124180303099825#cu")
        
        let apnsCerName = "cu_test"
        options?.apnsCertName = apnsCerName     
        options?.enableConsoleLog = true     
        options?.isDeleteMessagesWhenExitGroup = false     
        options?.isDeleteMessagesWhenExitChatRoom = false
        options?.isChatroomOwnerLeaveAllowed = false
        options?.usingHttpsOnly = true     
        
        EMClient.shared().initializeSDK(with: options)     
        let _ = EMCallManager.standard
        NotificationCenter.default.addObserver(self, selector: #selector(loginStateChange(nofi:)), name: NSNotification.Name(rawValue:KNOTIFICATION_LOGINCHANGE), object: nil)     
        
        let storyboard = UIStoryboard.init(name: "Launch", bundle: nil)     
        let launchVC = storyboard.instantiateViewController(withIdentifier: "EMLaunchViewController")     
        
        window = UIWindow.init(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        window?.rootViewController = launchVC
        window?.makeKeyAndVisible()
        
        parseApplication(application, didFinishLaunchingWithOptions: launchOptions)
        _registerAPNS()     
        
        return true
    }
    func registerRemoteNotification() {
        
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in
                if granted && error != nil {
                    
                    
                }
            })
            center.getNotificationSettings(completionHandler: { setting in
               
            })
            
        } else {
            
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil))
            
        }
        
    }
    @objc func loginStateChange(nofi: NSNotification) {
        if (nofi.object as! NSNumber).boolValue {
            let mainVC = EMMainViewController()     
            let nav = UINavigationController.init(rootViewController: mainVC)     
            window?.rootViewController = nav
        } else {
            let storyboard = UIStoryboard.init(name: "Register&Login", bundle: nil)     
            window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "EMLoginViewController")     
        }
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        EMClient.shared().applicationDidEnterBackground(application)     
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        EMClient.shared().applicationWillEnterForeground(application)     
    }
 
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        EMClient.shared().registerForRemoteNotifications(withDeviceToken: deviceToken, completion: nil)
        
        let data = NSData(data: deviceToken)
        var token = data.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
        token = token.replacingOccurrences(of: " ", with: "")
        let defaults = UserDefaults.standard
        defaults.set(token, forKey: "token")
        UMessage.registerDeviceToken(deviceToken)
    
    }
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        UMessage.didReceiveRemoteNotification(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
        
    }
    
    @available(iOS 10.0, *)
    //iOS10新增：处理前台收到通知的代理方法
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print(userInfo)
        completionHandler([.alert,.sound,.badge])
    }
    
    @available(iOS 10.0, *)
    //iOS10新增：处理后台点击通知的代理方法
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        //应用处于前台时的远程推送接受
        UMessage.setAutoAlert(false)
        UMessage.didReceiveRemoteNotification(userInfo)
        let info = userInfo as NSDictionary
        print(info)
        if info.count > 0 {
            if let tmpStr0 = info["eventId"] {
                if let eventId = (tmpStr0 as? String) {
                    let ifdeleted = info["delete"] as! Bool
                    print(info)
                    print(eventId)
                    print(ifdeleted)
                    print("处理前台收到通知的代理方法--应用处于前台时的远程推送接受--(notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!为true")
                    //通知owner删除了eventId代表的event
                    if ifdeleted == true {
                        
                    } else {
//                        //获得手机正在使用的语言
//                        let languageNow = EnStatic.languegeUsing()
//                        //login的owner的userid
//                        let loginOwner = EMClient.shared().currentUsername
//                        let dformatter = DateFormatter()
//                        dformatter.dateFormat = "yyyy-MM-dd"
//                        let date = Date()
//                        let dateTitle = dformatter.string(from: date)
//                        //必须全传进去，因为进去后先执行两个segue，后执行viewDidLoad，来不及合成dateTitle和取owner
//                        let statusPara = StatusPara(hasFriend:true,friendOwner:loginOwner!,loginOwner:loginOwner!,sourceViewControllerType:5,dateTitle:dateTitle,date:date,calendarTypeNumber:0,matchOrFree:0,languageNow:languageNow)
//                        let vc = EventDetailVC()
//                        vc.statusPara = statusPara
//                        vc.eventId = eventId
//                        let nav = UINavigationController.init(rootViewController: vc)
//                        window?.rootViewController = nav
                        
//
//                        let storyboard = UIStoryboard.init(name: "Launch", bundle: nil)
//                        let launchVC = storyboard.instantiateViewController(withIdentifier: "EMLaunchViewController")
//
//                        window = UIWindow.init(frame: UIScreen.main.bounds)
//                        window?.backgroundColor = UIColor.white
//                        window?.rootViewController = launchVC
//                        window?.makeKeyAndVisible()
                        
//                        parseApplication(application, didFinishLaunchingWithOptions: launchOptions)
                        
//
//                        weak var weakSelf = self
//                        let storyboard2 = UIStoryboard.init(name: "EventDetailVC", bundle: nil)
//                        let vc = storyboard2.instantiateInitialViewController() as! EventDetailVC
//                        vc.eid = eventId
//                        let nav = UINavigationController.init(rootViewController: vc)
//                        self.navigationController?.pushViewController(vc, animated: true)
                        
                        let isAppActivity = UIApplication.shared.applicationState == UIApplicationState.active
                        
//                        let storyboard2 = UIStoryboard.init(name: "EventDetailVC", bundle: nil)
//                        let detailVC = storyboard2.instantiateInitialViewController() as! EventDetailVC
//                        detailVC.eid = eventId
                        
                        
//                        if isAppActivity {
//                            
//                            let mainVC = self.window?.rootViewController as! EMMainViewController
//                            let curNav = mainVC.selectedViewController
//                            curNav?.navigationController?.pushViewController(detailVC, animated: true)
//                        }
//    
//                        else
//                        {
//                            
//                            let mainVC = EMMainViewController()
//                            let nav = UINavigationController.init(rootViewController: mainVC)
//                            window?.rootViewController = nav
//                            
//                            let curNav = mainVC.selectedViewController
//                            curNav?.navigationController?.pushViewController(detailVC, animated: true)
//                        }
//                        
    
                    }
                }
            }
        }
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        NSLog("register remote notification error", "")
    }
    
    fileprivate func _registerAPNS() {
        let application = UIApplication.shared     
        application.applicationIconBadgeNumber = 0     
        
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()     
            center.delegate = self      
            center.requestAuthorization(options: [.alert, .sound, .badge]) {
                (granted, error) in
                if granted {
                    DispatchQueue.main.async {
                        application.registerForRemoteNotifications()
                    }
                }
            }

        }else if #available(iOS 8.0, *){
            let settings = UIUserNotificationSettings.init(types: [.badge, .sound, .alert], categories: nil)     
            application .registerUserNotificationSettings(settings)     
        }
    }

    func getCurrentController() -> UIViewController? {
        guard let window = UIApplication.shared.windows.first else {
            return nil
        }
        var tempView: UIView?
        for subview in window.subviews.reversed() {
            if subview.classForCoder.description() == "UILayoutContainerView" {
                tempView = subview
                break
            }
        }
        
        if tempView == nil {
            tempView = window.subviews.last
        }
        
        var nextResponder = tempView?.next
        var next: Bool {
            return !(nextResponder is UIViewController) || nextResponder is UINavigationController || nextResponder is UITabBarController
        }
        
        while next{
            tempView = tempView?.subviews.first
            if tempView == nil {
                return nil
            }
            nextResponder = tempView!.next
        }
        return nextResponder as? UIViewController
    }
    
}

